export function copyToClipboard (string) {
  let copyInput = document.createElement('INPUT')
  copyInput.type = 'text'
  copyInput.style.width = '1px'
  copyInput.style.height = '1px'
  copyInput.style.border = 0
  copyInput.style.outline = 0
  document.body.appendChild(copyInput)
  copyInput.value = string
  copyInput.select()
  let result = document.execCommand('Copy')
  document.body.removeChild(copyInput)
  return result
}

export function scrollTo (end = 0) {
  document.body.scrollTop = end
  document.documentElement.scrollTop = end
}

export function scrollToSlow (end) {
  const cubic = value => Math.pow(value, 3)
  const easeInOutCubic = value => value < 0.5
    ? cubic(value * 2) / 2
    : 1 - cubic((1 - value) * 2) / 2

  const beginTime = Date.now()
  const beginValue = getScrollTop()
  const rAF = window.requestAnimationFrame || (func => setTimeout(func, 16))
  const frameFunc = () => {
    const progress = (Date.now() - beginTime) / 500
    const diff = end - beginValue
    if (progress < 1) {
      scrollTo(end - diff * (1 - easeInOutCubic(progress)))
      rAF(frameFunc)
    } else {
      scrollTo(end)
    }
  }
  rAF(frameFunc)
}

export function getScrollTop () {
  let scrollTop = 0
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop
  } else if (document.body) {
    scrollTop = document.body.scrollTop
  }
  return scrollTop
}

export function getScrollHeight () {
  return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}

export function getClientHeight () {
  let clientHeight = 0
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
  } else {
    clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
  }
  return clientHeight
}
